#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''
import logging
import json
from pycommon import Const
from pycommon import Pack as packet
from pycommon import Utils
import ClientBuild
import HallManager
import TimeCheck
import Center
import CenterBuild
import ServerConfig
import ClientFactory
import Game
import UserManager

def cmdLogin(client,pkt):
    cver, uid, session = packet.unpack("HIs", pkt)
    logging.debug(u"cmdLogin(), cver=%d, uid=%d, session=%s",cver,uid,session)
    ecode = Const.ERR_OK
    if not TimeCheck.instance.canLogin(uid):
        ecode = Const.ERR_WAIT_AND_RETRY
    if ecode != Const.ERR_OK:
        logging.debug(u"cmdLogin() uid=%d ecode=%d", uid, ecode)
        client.sendPacket(ClientBuild.clientLogin(ecode))
        client.goToClose()
        TimeCheck.instance.addLoginFail(uid)
        return
    client.onLoginRequest(uid, session)
    ClientFactory.instance.mapClient(uid,client)
    logging.debug(u"checkUser() uid=%d session=%s ip=%s", uid, session, client.getIp())
    Center.instance.sendPacket(CenterBuild.checkUser(uid, session, client.getId()))
    pass

def cmdLogout(client,pkt):
    logging.debug(u"cmdLogout() uid=%d", client.getUid())
    client.onLogoutRequest()
    pass

def cmdJoinTable(client,pkt):
    hallId,tableId,tableIdStr = packet.unpack("HHs", pkt)
    tableIdStr = Utils.pstr2u(tableIdStr)
    code = Const.ERR_OK
    uid = client.getUid()
    user = UserManager.instance.getUser(uid)
    if user.getTableId() != -1:
        #reconnect
        logging.debug("333333333333333333333333333333333333333333333333333333333333")
        pass
    else:
        code = UserManager.instance.onUserEnter(uid,hallId,tableId,tableIdStr)
        logging.debug("cmdJoinTable code = %d",code)
        tableInfo = {}
        if code == Const.ERR_OK:
            hall = HallManager.instance.getHall(hallId)
            table = hall.getTable(tableId)
            tableInfo = table.getTableInfo()
            tableInfo = json.dumps(tableInfo)
        tableInfo = json.dumps(tableInfo)
        client.sendPacket(ClientBuild.joinTable(code,tableInfo))
        Center.instance.sendPacket(CenterBuild.enterTable(tableIdStr,uid))

__cmdTable = {
        Const.CMD_C2GAME_LOGIN           : cmdLogin,
        Const.CMD_C2GAME_LOGOUT          : cmdLogout,
        Const.CMD_C2GAME_JOIN            : cmdJoinTable
    }

def parse(client,cmd,pkt):
    logging.debug(u"ClientParse cmd = %d",cmd)
    func = __cmdTable.get(cmd)
    if func:
        func(client,pkt)
        return
    if client.isLogined():
        Game.instance.parsePacket(client, cmd, pkt)
    

if __name__ == "__main__":
    pass